"""
File:views.py
Author: anning
Date:-04-12
Connect:792910452@qq.com
Description:
创建蓝图有三步：
1）在蓝图下的__init__.py文件中创建蓝图
2）在蓝图下的views.py文件中应用蓝图
3）在蓝图所属的文件app中的__init__.py文件中注册蓝图
"""
# 2）应用蓝图
from flask import render_template, abort, flash, redirect, url_for

from app import db
from app.models import User
from app.user import user
from flask_login import login_required, current_user

from app.user.forms import EditProfileForm


@user.route('/user/<id>')
@login_required
def get_user(id):
    user=User.query.filter_by(id=id).first()
    if user is None:
        abort(404)   # 抛出一个404异常
    else:            # 由于这里抛出异常，其实不用else直接返回也可以
        #总任务数，已完成任务数，未完成任务数
        #print(user.todos)
        todos=user.todos
        all_count=len(user.todos)
        undo_count=done_count=0
        for todo in todos:
            if todo.status:
                done_count += 1
            else:
                undo_count += 1
        return render_template('user/user.html',user=user,
                               all_count=all_count,
                               done_count=done_count,
                               undo_count=undo_count)


@user.route('/changepwd/<id>')
def change_password(id):
    return 'change password'


@user.route('/edit-profile',methods=['POST','GET'])
def edit_profile():
    form=EditProfileForm()
    if form.validate_on_submit():
        current_user.name=form.name.data
        current_user.location=form.location.data
        current_user.about_me=form.about_me.data
        db.session.add(current_user)
        db.session.commit()
        flash('用户配置信息更新成功',category='success')
        return redirect(url_for('user.get_user',id=current_user.id))
    form.name.data=current_user.name
    form.location.data=current_user.location
    form.about_me.data=current_user.about_me
    return render_template('user/edit_profile.html',form=form)
